<template>
    <div class="login">
        <el-card shadow="hover">
            <div slot="header">
                <span>登录</span>
            </div>

            <el-form
                :model="loginForm"
                :rules="loginRules"
                ref="loginFromRef"
                size="small"
            >
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="loginForm.username"></el-input>
                </el-form-item>

                <el-form-item label="密码" prop="password">
                    <el-input
                        type="password"
                        v-model="loginForm.password"
                    ></el-input>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="submit">登录</el-button>
                </el-form-item>
            </el-form>

            <el-row type="flex" justify="end">
                <el-link type="primary" :underline="false" href="/register"
                    >还没账号吗？去注册</el-link
                >
            </el-row>
        </el-card>
    </div>
</template>

<script>
export default {
    data() {
        return {
            loginForm: {
                username: '',
                password: '',
            },
            loginRules: {
                username: [
                    {
                        required: true,
                        message: '请输入用户名',
                        trigger: 'change',
                    },
                ],
                password: [
                    {
                        required: true,
                        message: '请输入密码',
                        trigger: 'change',
                    },
                ],
            },
        };
    },
    methods: {
        async submit() {
            try {
                await this.$refs.loginFromRef.validate();
            } catch (error) {
                this.$message.error('表单校验不通过');
                return;
            }
            const res = await this.$http.post('/login', this.loginForm);
            if (res.code !== 200) {
                this.$message.error(res.message);
                return;
            }
            // 存储 token
            window.sessionStorage.setItem('token', res.data.token);
            // 存储菜单
            window.sessionStorage.setItem(
                'menus',
                JSON.stringify(res.data.menus),
            );
            // 存储用户信息
            window.sessionStorage.setItem(
                'profile',
                JSON.stringify(res.data.profile),
            );
            // 跳转到首页
            this.$router.push('/');
        },
    },
};
</script>

<style lang="less" scoped>
.login {
    background-color: #eee;
    min-height: 100vh;
}

.el-card {
    width: 450px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.el-form {
    .el-button {
        width: 100%;
    }
}
</style>
